﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace PrintLabel
{
    public static class BitmapOper
    {
        public static string ImageToBase64(Image bmp)
        {
            string result;
            try
            {
                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0L;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                result = Convert.ToBase64String(arr);
            }
            catch (Exception ex)
            {
                result = null;
            }
            return result;
        }

        public static string ImgToBase64String(Bitmap bmp)
        {
            string result;
            try
            {
                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0L;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                result = Convert.ToBase64String(arr);
            }
            catch (Exception ex)
            {
                result = null;
            }
            return result;
        }

        public static Bitmap Base64StringToImage(string strbase64)
        {
            Bitmap result;
            try
            {
                byte[] arr = Convert.FromBase64String(strbase64);
                MemoryStream ms = new MemoryStream(arr);
                Bitmap bmp = new Bitmap(ms);
                ms.Close();
                result = bmp;
            }
            catch (Exception ex)
            {
                result = null;
            }
            return result;
        }
    }
}
